<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-25 09:36
 * Modified Time: 2019-06-25 09:36
 * Version: 2.0
 */

namespace App\Modules\Employee\Repositories;

use App\Exceptions\AllValidatorException;
use App\Exceptions\NotFoundException;
use App\Lib\Utilities;
use App\Models\User;
use App\Modules\Employee\Criterias\FindTokenCriteria;
use App\Modules\Employee\Criterias\GetStoreBarberListCriteria;
use App\Modules\Employee\Criterias\GetWxBarberStoreInfoDetailCriteria;
use App\Modules\Employee\Validators\EmployeeValidator;
use App\Modules\Member\Repositoryies\ScheduleRepository;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\Store\Repositories\StoreRepository;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;

class EmployeeRepository extends BaseRepository
{
    /**
     * Specify Model class name
     * @return string
     */
    public function model()
    {
        return User::class;
    }

    /**
     * Specify Validator class name
     * @return mixed
     */
    public function validator()
    {
        return EmployeeValidator::class;
    }

    /**
     * 设置token
     * @param int $length
     * @return string
     */
    private static function createToken()
    {
        $tokenLength = config('app.tokenLength') ? config('app.tokenLength') : 60;
        return Str::random($tokenLength);
    }

    /**
     * 设置token的有效期
     */
    private static function tokenExpire()
    {
        $expireTime = config('app.expireTime') ? config('app.expireTime') : 1;
        return strtotime("+" . $expireTime . " month");
    }


    /**
     * App端用户注册
     * @param $mobile
     * @param $password
     * @return mixed
     */
    public function register($mobile, $password)
    {
        $params = [
            'token' => self::createToken(),
            'token_expire' => self::tokenExpire(),
            'username' => $mobile,
            'password' => $password,
            'mobile' => $mobile,
            'nick' => $mobile,
        ];
        $userInfo = $this->create($params);
        $userInfo->invite_code = str_pad($userInfo->id, 6, '0', STR_PAD_LEFT);
        $userInfo->save();
        return $userInfo;
    }


    /**
     * 查询用户token是否是在有效期内
     */
    public function isPass($requestData)
    {
        $user = $this->getByCriteria(new FindTokenCriteria($requestData))->first();
        return $user->token_expire > time() ? $user : false;
    }

    /**
     * App端用户修改密码
     * @param $requestData
     * @param $userInfo  查询用户示例
     * @return mixed
     */
    public function editPassword($requestData, $userInfo)
    {
        $userInfo->password = $requestData['password'];
        return $userInfo->save();
    }


    /**
     * 查询用户是否存在通过手机号
     */
    public function isExitedByMobile($mobile)
    {
        return $this->findByField('mobile', $mobile)->first();
    }


    /**
     * 更新token
     * @param $userInfo
     * @return mixed
     */
    public function updateToken($userInfo)
    {
        $userInfo->token = self::createToken();
        $userInfo->token_expire = self::tokenExpire();
        $userInfo->save();
        return $userInfo;
    }

    /**
     * 更新密码
     * @param $userInfo
     * @param $newPassword
     * @return mixed
     */
    public function updatePassword($userInfo, $newPassword)
    {
        $userInfo->password = $newPassword;
        $userInfo->save();
        return $userInfo;
    }


    /**
     * 获取用户登录的详细信息
     * @param $userId
     * @return mixed
     */
    public function getUserInfo($userId)
    {
        return $this->with('picture')->with('userStore')->find($userId);
    }

    /**获取用户的基本信息
     * @param $userId
     * @return mixed
     * @author Happy dong
     * @modifiedTime 2019-07-31 13:56
     */
    public function getUserBaseInfo($userId)
    {
        return $this->with('picture')->find($userId);
    }

    /**
     * 验证参数完整性
     * @param $requestData
     * @return bool
     * @throws NotFoundException
     */
    protected function checkLogin($requestData)
    {
        if (!isset($requestData['mobile']) || empty($requestData['mobile']) || !isset($requestData['password']) || empty($requestData['password'])) {
            throw new NotFoundException(['msg' => '手机号或者密码参数不完整']);
        }
        return true;
    }

    /**
     * 添加理发师给店铺
     * @param $requestData
     * @return mixed
     * @throws AllValidatorException
     * @throws NotFoundException
     * @throws ValidatorException
     */
//    public function addBarber($userId,$storeId){
//	    // 插入中间表的数据
//	    $userStoreData = $userStore->count() > 1 ?  ['sid'=>$requestData['store_id'],'uid'=>$requestData['user_id'],'rid'=>config('constant.role.barber'), 'is_work'=> 0, 'is_default' => 0] : ['sid'=>$requestData['store_id'],'uid'=>$requestData['user_id'],'rid'=>config('constant.role.barber'), 'is_work'=> 1, 'is_default' => 1];
//
//	    $store->user()->attach($requestData['user_id'], $userStoreData);
//	    return $store;
//    }

    /**
     * 查询用户是否存在
     * @param $userId
     * @return mixed
     * @throws NotFoundException
     */
    public function isExited($userId)
    {
        $userInfo = $this->find($userId);
        if (empty($userInfo)) {
            throw new NotFoundException(['msg' => '用户不存在']);
        }
        return $userInfo;
    }


    /**
     * 该店铺是不是理发的默认店铺
     * @param $userId
     * @param $storeId
     * @return mixed
     * @throws NotFoundException
     */
    public function isDefaultByStoreId($userId, $storeId)
    {
        $userStore = $this->isExited($userId)->store()->find($storeId);
        if (empty($userStore)) {
            throw new NotFoundException(['msg' => '该理发师不属于该理发店！']);
        }
        return $userStore->pivot->is_default;
    }





    /**
     * 计算店铺所有员工的每日基本工资
     * @param $userIds
     * @param $storeId
     * @param int $role
     * @return float|int
     * @author Happy dong
     * @modifiedTime 2019-09-19 14:32
     */
    public function getStoreDailySalary($userIds, $storeId, $role, $date)
    {
        $role = empty($role) ? config('constant.role.barber') : $role;
        $peopleSalary = 0;
        foreach ($userIds as $id) {
            $peopleSalary += (new \App\Modules\System\Repositories\UserStoreRepository())->getUserDailySalary($id, $storeId, $role, $date);
        }
        return $peopleSalary;
    }


    /**
     * 获取用户在某店铺的店铺信息
     * @param $userId
     * @param $store
     * @return array
     */
    public function getStoreInfo($userId, $store)
    {
        $res = $this->model->selectRaw('*')->where('id', $userId)->with([
            'store' => function ($query) use ($store) {
                $query->selectRaw('*')->when($store, function ($query) use ($store) {
                    return $query->where('id', $store)->limit('1');
                });
            }
        ])->first()->toArray();

        return isset($res['store']) ? $res['store'] : [];
    }

	/**
	 * 根据手机号判断用户是否存在
	 * @param $mobile
	 * @return bool
	 */
    public function checkUserMobileExist($mobile)
    {
        if($this->findByField(['mobile' => $mobile])->first()) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 根据邀请码获取用户信息
     */
    public function getUserByInviteCode($invite_code)
    {
        return $this->findByField(['invite_code' => $invite_code])->first();
    }


    public function InviteCodeIsExisted($invite_code){
	    $res = $this->findByField(['invite_code' => $invite_code])->first();
	    if(empty($res)){
	    	throw new NotFoundException(['msg'=>'邀请码不存在！']);
	    }
	    return true;
    }


    /*
     * 根据id获取邀请码
     */
    public function getInviteCodeByUserId($user_id)
    {
        return $this->find($user_id)->invite_code;
    }

    /**
     * 获取理发师列表
     * @param $storeId
     * @param $pageSize
     * @return array
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getStoreBarberList($storeId, $pageSize)
    {
        $list = $this->pushCriteria(new GetStoreBarberListCriteria($storeId))->paginate($pageSize, ['*'], 'paginate');
        return Utilities::dealPage($list);
    }


	/**
	 * 设置用户基本工资 pass
	 * @param $userId
	 * @param $salary
	 * @return mixed
	 * @throws NotFoundException
	 */
//    public function setBaseSalary($userId, $salary)
//    {
//        $userInfo = $this->find($userId);
//        if (empty($userInfo)) {
//            throw new NotFoundException(['msg' => "用户不存在"]);
//        }
//        $userInfo->salary = $salary;
//        return $userInfo->save();
//    }

    /**
     * 理发师获取本人信息
     * @param $user_id
     * @param $nick
     * @param $portrait
     * @param $introduction
     * @param $mobile
     * @param $wechat
     */
    public function updateEmployeeInfo($user_id, $nick, $portrait, $introduction, $mobile, $wechat)
    {
        $data = [];

        if ($nick) {
            $data['nick'] = $nick;
        }
        if ($portrait) {
            $data['portrait'] = $portrait;
        }
        if ($introduction) {
            $data['introduction'] = $introduction;
        }
        if ($mobile) {
            throw new AllValidatorException(['msg'=>'老板 联系手机号暂不可修改哦']);
            $data['mobile'] = $mobile;
        }
        if ($wechat) {
            $data['wechat'] = $wechat;
        }

        return $this->update($data, $user_id);

    }

    public function getEmployeeProfile($user_id)
    {
        return $this->model->select([
            'profile_picture as profile_picture_id',
            'picture.image as profile_picture',
            'profile_video as profile_video_id',
            'video.thumb',
            'video.url as profile_video'
        ])->leftJoin('picture', 'user.profile_picture', 'picture.id')
            ->leftJoin('video', 'user.profile_video', 'video.id')
            ->where('user.id', $user_id)
            ->first();
    }

    public function updateEmployeeProfile($user_id, $profile_picture, $profile_video)
    {
        $data = [];
        $data['profile_video'] = $profile_video;
        $data['profile_picture'] = $profile_picture;
        return $this->update($data, $user_id);
    }


    public function getOrderPointData($storeId, $startDate, $endDate)
    {
        return DB::select('SELECT
	u.id,
	u.nick,
	u.username,
	u.portrait,
	p.image,
	sum(
		CASE
		WHEN (o.is_appoint = 1) THEN
			1
		ELSE
			0
		END
	) AS appoint_count,
	count(o.finish_time) AS order_count 
	FROM hx_user AS u LEFT JOIN hx_user_store AS s ON u.id = s.uid  LEFT JOIN hx_picture AS p ON u.portrait = p.id LEFT JOIN hx_order AS o ON u.id = o.barber_id  and FROM_UNIXTIME(o.finish_time,\'%Y-%m-%d\') <= "' . $startDate . '" and FROM_UNIXTIME(o.finish_time,\'%Y-%m-%d\') >="' . $endDate . '"  WHERE s.sid = "' . $storeId . '"   GROUP BY u.id');
    }


    public function getUserSalaryDataByStoreId($storeId, $startDate, $endDate)
    {

//	    SELECT a.user_id, sum(a.amount + a.royalty) AS amounts, FROM_UNIXTIME(a.salary_date, \'%Y-%m\') AS months FROM hx_salary AS a WHERE a.store_id ="' . $storeId . '" AND FROM_UNIXTIME(a.salary_date, \'%Y-%m-%d\') <= "' . $startDate . '" AND FROM_UNIXTIME(a.salary_date, \'%Y-%m-%d\') >= "' . $endDate . '" GROUP BY a.user_id, months

        return DB::select('SELECT users.id, users.nick, users.image, salarys.amounts, salarys.months FROM ( SELECT u.id, u.nick, p.image FROM hx_user AS u LEFT JOIN hx_user_store AS s ON u.id = s.uid LEFT JOIN hx_picture AS p ON p.id = u.portrait WHERE s.sid="' . $storeId . '" GROUP BY u.id ) AS users LEFT JOIN (
         select ns.user_id,sum(ns.amount+ns.`royalty`) as amounts, FROM_UNIXTIME(ns.salary_date, \'%Y-%m\') as months from (SELECT distinct a.salary_date, a.user_id,a.amount,a.royalty, FROM_UNIXTIME(a.salary_date, \'%Y-%m-%d\') AS days   FROM hx_salary AS a WHERE a.store_id ="'.$storeId.'" AND FROM_UNIXTIME(a.salary_date, \'%Y-%m-%d\') <= "'.$startDate.'" AND FROM_UNIXTIME(a.salary_date, \'%Y-%m-%d\') >= "'.$endDate.'") as ns group by ns.`user_id`,months) AS salarys ON users.id = salarys.user_id');
    }

    /**
     * 保存用户头像
     * @param $user_id
     * @param $portrait
     */
    public function updatePortrait($user_id, $portrait)
    {
        $this->update(['portrait' => $portrait], $user_id);
    }


    public function getUserInfoByStoreIdDetails($storeId,$userId){
    	return  $this->getByCriteria(new GetWxBarberStoreInfoDetailCriteria($storeId,$userId))->first();
    }

	/**
	 * 获取用户信息
	 * @param $userId
	 * @return mixed
	 */
    public static function getBarberUserInfoById($userId,$onlyName=false){
//    	return empty($userId) ? [] : User::getUsernamePortraitInfoById($userId,$onlyName);
    	if(empty($userId)) return null;
    	$userInfo = User::getUsernamePortraitInfoById($userId,$onlyName);
    	if($onlyName) return $userInfo;
    	if(isset($userInfo->picture->image)) {
		    $userInfo->portrait = $userInfo->picture->image;
	    }
	    unset($userInfo->picture);
    	return $userInfo;
    }

	/**
	 * 县令币余额
	 * @param $userId
	 * @return mixed
	 * @throws NotFoundException
	 */
    public function getUserCoinInfo($userId){
    	$info = $this->isExisted($userId);
    	return $info->coin;
    }


    public function isExisted($userId){
    	$userInfo = $this->find($userId);
    	if(empty($userInfo)){
    		throw new NotFoundException(['msg' => '用户信息不存在']);
	    }

    	return $userInfo;
    }
}
